<template>
	<div class="system-user-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
      <el-button size="default" type="primary"  @click="onDownloadImport()">
        <el-icon>
          <Download />
        </el-icon>
        模板下载
      </el-button>
			<template #footer>
				<el-upload
					ref="upload"
					class="upload-demo"
					drag
					action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
					:limit="1"
					:on-exceed="handleExceed"
					:on-change="handleChange"
					:auto-upload="false"
          :disabled="state.disabled"
				>
					<el-icon class="el-icon--upload"><upload-filled /></el-icon>
					<div class="el-upload__text">拖拽文件到这里或者<em>点击上传</em></div>
					<template #tip>
						<div class="el-upload__tip">
							<el-row justify="end" align="middle">
								<el-col :span="10" :pull="8" >
									<el-text class="mx-1" type="danger">只允许上传模板文件，仅支持xls、xlsx！</el-text>
								</el-col>
								<el-col :span="6">
									<el-button @click="submitUpload" size="default" type="success" style="text-align: right" :disabled="state.disabled">执行导入</el-button>
								</el-col>
							</el-row>
						</div>
					</template>
				</el-upload>
				<div class="dynamic-log-container" style="margin-top: 20px; margin-bottom: 20px">
          <el-row align="middle" :gutter="15" style="margin-bottom: 20px" v-if="state.progressVisable">
            <el-col :span="4">
              <el-text class="mx-1" type="primary" size="large">导入进度</el-text>
            </el-col>
            <el-col :span="20">
              <el-progress
                  :percentage="state.percentage"
                  :stroke-width="15"
                  :status="state.progressStatus"
                  striped
                  striped-flow
                  :duration="10"
              />
            </el-col>
          </el-row>
					<el-card shadow="always" style="text-align: left; height: 380px">
						<template #header>
							<span>动态日志</span>
						</template>
						<el-scrollbar max-height="300px" ref="scrollbarRef">
							<div class="log-content" ref="logContent">
								<div v-for="(log, index) in logs" :key="index" class="log-item">
									{{ log }}
								</div>
							</div>
						</el-scrollbar>
					</el-card>
				</div>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default" :disabled="state.disabled">清除记录</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemUserDialog">
import { nextTick, reactive, ref } from 'vue';
import {Download, UploadFilled} from '@element-plus/icons-vue';
import { ElMessage, ElScrollbar, genFileId, UploadInstance, UploadProps, UploadRawFile } from 'element-plus';
import * as XLSX from 'xlsx';
import { userApi } from '/@/api/user';

const { studentImport,studentImportMQMessage } = userApi();

const upload = ref<UploadInstance>();
// 获取 log-content 元素
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>();
const logContent = ref<HTMLElement | null>(null);
// 日志列表
const logs = ref<string[]>([]);
// 定义子组件向父组件传值/事件
// eslint-disable-next-line @typescript-eslint/no-unused-vars,no-unused-vars
const emit = defineEmits(['refresh']);

// 定义变量内容
const state = reactive({
	file: null,
	json: [],
  disabled: false,
  progressVisable:false,
  progressStatus:'',
  percentage:0,
  percentLength:0,
	dialog: {
		isShowDialog: false,
		type: '',
		title: '批量导入学生',
	},
});

const handleExceed: UploadProps['onExceed'] = (files) => {
	upload.value!.clearFiles();
	const file = files[0] as UploadRawFile;
	file.uid = genFileId();
	upload.value!.handleStart(file);
};
const handleChange: UploadProps['onChange'] = (uploadFile) => {
	const file = uploadFile;
	state.file = file.raw;
	if (state.file.type == 'application/vnd.ms-excel' || state.file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
		return true;
	} else {
		ElMessage.error('仅支持xls、xlsx！');
		upload.value!.clearFiles();
		return false;
	}
};
//处理excel导入
const submitUpload = () => {
	//处理excel文件
	// 判断文件是否存在
	if (!state.file) {
		ElMessage.error('请选择一个文件进行上传！');
		return;
	}
	const reader = new FileReader();
	reader.onload = (e) => {
		const data = new Uint8Array(e.target?.result as ArrayBuffer);
		const workbook = XLSX.read(data, { type: 'array' });
		const firstSheetName = workbook.SheetNames[0];
		const worksheet = workbook.Sheets[firstSheetName];
    state.json = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

    // 过滤掉空行
    state.json = state.json.filter(row => row.some(cell => cell !== ''));
    state.percentLength = state.json.length;
    importFile();
	};
	reader.readAsArrayBuffer(state.file);

};

const importFile = async () => {
  state.disabled = true;
  state.progressVisable = true;
  state.percentage= 0;
  state.progressStatus = '';
  const ids: string[] = [];
  addLog(`处理文件开始`);
  let errorStatus= '';
  if(state.percentLength<2){
    errorStatus = 'exception';
    addLog(`文件没检查到数据！请检查文件是否正确！`)
  }
  for (const [index, row] of state.json.entries()) {
    // 处理每一行数据
    // 判断第一行是否正确
    if (index == 0) {
      addLog(`文件格式检查开始`);
      if (
          row[0] == '学校' &&
          row[1] == '学习阶段' &&
          row[2] == '年级' &&
          row[3] == '班级' &&
          row[4] == '姓名' &&
          row[5] == '学号' &&
          row[6] == '证件类型' &&
          row[7] == '证件号码' &&
          row[8] == '入学年级' &&
          row[9] == '性别' &&
          row[10] == '父亲电话' &&
          row[11] == '母亲电话'
      ) {
        addLog(`文件格式检查通过！`);
        continue;
      } else {
        ElMessage.error('请检查文件格式是否正确！');
        addLog('文件格式检查不通过！请检查文件格式是否正确！');
        errorStatus = 'exception';
        break;
      }
    }
    let uploadRequest = {
      school: row[0],
      stage: row[1],
      grade: row[2],
      className: row[3],
      nickName: row[4],
      username: row[5],
      idType: row[6],
      userIdCardNumber: row[7],
      nth: row[8],
      gender: row[9],
      fatherMobile: row[10],
      motherMobile: row[11],
    };
    try {
      const res = await studentImport(uploadRequest);
      if (res.status === 200) {
        addLog(`处理数据: ${JSON.stringify(row)}`);
        addLog(`处理完成,` + res.data.msg);
        ids.push(res.data.id);
        onProgress();
      }
    } catch (error:any) {
      addLog(`处理数据: ${JSON.stringify(row)}`);
      if(typeof error.data=='string')
        addLog("处理报错，异常为：" + error.data);
      else
        addLog("处理报错，异常为：" + error.data.errMsg);
    }
  }
  addLog(`处理文件结束`);
  try {
    const res = await studentImportMQMessage(
        {
          id: ids.join(",")
        })
    if (res.status === 200) {
      addLog(`处理消息队列成功`);
    } else
      addLog(`处理消息队列失败`);
  }  catch (error:any) {
    addLog(`处理消息队列失败`);
  }
  state.percentage = 100;
  state.disabled = false;
  if(errorStatus=='')
    state.progressStatus = 'success';
  else
    state.progressStatus = 'exception';
};

// 添加日志的方法
const addLog = (newLog: string) => {
	logs.value.push(newLog + ` - ${new Date().toLocaleTimeString()}`);
	// 滚动到底部
	nextTick(() => {
		if (logContent.value) {
			scrollbarRef.value!.setScrollTop(logContent.value.scrollHeight);
		}
	});
};
const onDownloadImport = () => {
  window.open("https://obs-nmbt.cucloud.cn/deer-base/excel/学生导入模板.xls")
}
// 打开弹窗
const openDialog = () => {
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
	upload.value!.clearFiles();
	logs.value = [];
	state.file = null;
	state.json = [];
  state.progressVisable=false;
  state.progressStatus='';
  state.percentage=0;
  state.percentLength=0;
};

//进度条增长
const onProgress = () => {
  state.percentage = parseFloat(((state.percentage + 1 / state.percentLength * 100).toFixed(2)));
};

// 取消
const onCancel = () => {
	closeDialog();
};


// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped>
.dynamic-log-container {
	width: 100%;
	max-width: 800px;
	margin: 0 auto;
}

.log-content {
	padding: 10px;
}

.log-item {
	margin-bottom: 5px;
}
</style>